"use strict"
const mvc = require('cosjs.mvc');
exports.format = {
    "id":'fs',
    "name":"飞书",

    // "verify": {
    //     "sandbox": "http://$MAIN_HOST/auth/myProfile",
    // },

    // "access":{
    //     "sandbox": "http://$MAIN_HOST/auth/myProfile",
    // },

    "fields":{
        "appid" :{'type':'string','val':'421735818853085188','name':"AppId"},
        "secret" :{'type':'string','val':'5lM1PQqkVZB15UJ1CYUXrZiS40fJO5OCFCv1','name':"AppSecret"},
    }
};
const login_url = "https://api-sdk-gameplus.meetsocial.com/auth/myProfile"

//登录与认证TOKEN
exports.login = function () {
    let code = this.get("code","string");
    if(!code){
        return this.error("token empty");
    }
    // let tokenKey = this.opensdk['_id'];
    // let tokenModel = mvc.model.redis('token',this.branch);
    // let host = login_url;
    // let args = {"appid":this.opensdk.setting.appid,"secret":this.opensdk.setting.secret,"code":code,"grant_type":"authorization_code"};
    // return code;
    return this.library("request/get", login_url, {},true,{"Authorization": code}).then(ret=>{
        // if( ret["errcode"] ){
        //     return this.error(`${ret["errmsg"]}[${ret["errmsg"]}]` )
        // }
        // //let expires = Date.now() + body["expires_in"] * 1000;
        // let token = {};
        // //token['unionid'] = ret["unionid"];
        // token['access']  = ret["access_token"];
        // token['expire'] = Date.now() + ret["expires_in"] * 1000;
        // token['refresh'] = ret["refresh_token"];
        console.log("http res:",ret);
        
        return ret["data"]["id"];
    })
    return tokenModel.get(tokenKey).then(ret=>{
        //console.log('tokenModel get',ret)
        if(ret){
            return ret;
        }
        //获取新的token
        return tokenModel.lock(tokenKey).then(ret=>{
            if(ret.length > 0){
                return this.error("tryAgain",5);
            }
            else {
                return get_facebook_access.call(this);
            }
        }).then(ret=>{
            return tokenModel.set(tokenKey,ret['access'],ret['expire']).then(ret=>ret['access'])
        })
    }).then(ret=>{
        let url = this.opensdk.status > 0 ? exports.format.verify.production : exports.format.verify.sandbox;
        let data = {"access_token":ret,"input_token":token}
        //console.log("request",url,JSON.stringify(data))
        return this.library("request/get",url,data,true);
    }).then(ret=>{
        //console.log("request ret",JSON.stringify(ret))
        if(!ret){
            return this.error('facebook_token_empty',ret);
        }
        if(ret['error']){
            return this.error(ret['error']['type'],ret['error']['message']);
        }
        if(!ret['data'] || !ret['data']["user_id"]){
            return  this.error("facebook_login_error",ret)
        }
        return  ret['data']["user_id"];
    })
};